#!/usr/bin/ruby
# 动弹脚本
require 'net/http'
require 'json'
require 'uri'

cookies = {
    moli: {
      cookie:"y%2BYus%2FnuhoFhX4F031DQDyZPX6%2FnMJ88FgDhPYCeySvqVRp5KygURcb754kk3lSm8oLoYp%2BF%2BIudRpE5RvtjGh8EyKnieg5kCWi6zkFv3%2Bacp0e1pmlxiwUQAvxMHKyxOZciVpos%2Fr3JtsOwlnuVPw%3D%3D",
      user_code: "290xHOP7PsPoNsHRiaJRarWT2euIGpVMVAptomdL",
      user: 1265071
    }
}

def test(cookie)
  puts "test ing"
  Net::HTTP.start('www.oschina.net', 80) do |http|
    response = http.post('/action/tweet/pub', 
      "user_code=#{cookie[:user_code]}&user=#{cookie[:user]}&msg=#{URI.escape('this is auto dongtan')}",
      {'Cookie'=>"oscid=#{cookie[:cookie]}"}
    )
    puts response.body
  end
end

def send_dongtan(name, cookie)
  pm25 = get_pm25

  msg = rand(10) <= 5 ? "今日深圳PM2.5: #{pm25}" : msg_array
  Net::HTTP.start('www.oschina.net', 80) do |http|
    response = http.post('/action/api/tweet_pub',
      "uid=#{cookie[:user]}&msg=#{URI.escape(msg)}",
      {'Cookie'=>"oscid=#{cookie[:cookie]}",
       'User-Agent'=>'Mozilla/5.0 (Linux; U; Android 6.0.1; zh-CN; ZUK Z2131 Build/MMB29M) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}
    )
    puts response.body
  end
end

def msg_array
  "现在时间：#{Time.now.strftime("%Y-%m-%d %T")}"
end


def get_pm25
  body = "{}"
  Net::HTTP.start('apis.baidu.com', 80) do |http|
    response = http.get('/heweather/weather/free?city=shenzhen', 
      {'apikey'=>"edba2b9cb6fa86ec4ce68ee966ec3505"}
    )
    body = response.body
  end
  # puts body
  json = JSON.parse(body)
  if json.class == Hash
    pm25 = json["HeWeather data service 3.0"][0]["aqi"]["city"]["pm25"]
    qlty = json["HeWeather data service 3.0"][0]["aqi"]["city"]["qlty"]
    return "#{pm25} #{qlty}"
  end
rescue
  return "蛤蛤"
end


# test( cookies[:moli])
# puts get_pm25

cookies.each do |k,v|
  send_dongtan(k.to_s,v)
end